//创建用户相关的小仓库
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { reqLogin, reqUserInfo } from '@/api/user'
import type { ILoginForm, ILoginResponse } from '@/api/user/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
// 引入常量路由
import { constantRoute } from '@/router/routes'
import type { RouteRecordRaw } from 'vue-router'

/// 组合式写法setup Store
const useUserStore = defineStore('User', () => {
  // 用户唯一标识的token
  const token = ref<string>(GET_TOKEN())

  //用户名称
  const username = ref<string>('')

  //用户的头像
  const avatar = ref<string>('')

  //仓库存储生成菜单需要的路由
  const menuRoutes = ref<RouteRecordRaw>(constantRoute)

  // 登录请求
  const userLogin = async (data: any): Promise<string> => {
    const result: any = await reqLogin(data)

    /// 登录请求成功200——>token
    if (result.code === 200) {
      token.value = result.data.token
      // token 本地持久化
      SET_TOKEN(token.value)
      return 'ok'
    } else {
      return Promise.reject(new Error(result.data.message))
    }
  }

  // 获取用户信息的方法
  const userInfo = async (): string => {
    // 获取用户信息进行存仓库 【头像、名字】
    let result = await reqUserInfo()
    // 如果获取用户信息成功就存储
    if (result.code === 200) {
      username.value = result.data.checkUser.username
      avatar.value = result.data.checkUser.avatar
      return 'of'
    } else {
      return Promise.reject('获取用户信息失败')
    }
  }

  //退出登录
  const userLogOut = () => {
    token.value = ''
    username.value = ''
    avatar.value = ''
    REMOVE_TOKEN()
  }

  return {
    token,
    menuRoutes,
    userLogin,
    userInfo,
    username,
    avatar,
    userLogOut,
  }
})

export default useUserStore
